package com.cmhk.zmail

import com.cmhk.utils.RSAUtils
import org.springframework.beans.factory.InitializingBean

import javax.mail.AuthenticationFailedException
import javax.mail.MessagingException

class MailTokenService implements InitializingBean {
    def grailsApplication
    def publicKey
    def privateKey
    MailService mailService

    @Override
    void afterPropertiesSet() throws Exception {
        def mailSecurityConfig = grailsApplication.config.mailSecurity
        def modulus = mailSecurityConfig.modulus
        def public_exponent = mailSecurityConfig.public_exponent
        def private_exponent = mailSecurityConfig.private_exponent
        publicKey = RSAUtils.getPublicKey(modulus, public_exponent);
        privateKey = RSAUtils.getPrivateKey(modulus, private_exponent);
    }


    public String getToken(String username, String password) {
        String data = "${username}\n${password}"
        return RSAUtils.encryptByPublicKey(data, publicKey)
    }

    public Map decryptToken(String cipherText) {
        String plainText = RSAUtils.decryptByPrivateKey(cipherText, privateKey)
        def keys = plainText.tokenize()
        if (keys.size() == 2) {
            def username = keys[0]
            def password = keys[1]
            return [username: username, password: password]
        } else {
            return [:]
        }
    }


    public Boolean authenticate(String token) throws AuthenticationFailedException,MessagingException {
        def authData = decryptToken(token)
        if (authData) {
            println "auth mail use ${authData}"
            return mailService.authenticate(authData.username, authData.password)
        } else
            return false

    }


}
